#coding: utf8
'''
==================================================================================
Created on 2020-10-26
Author: Simon
==================================================================================
'''
import calendar
from src.config import Config as C
from datetime import datetime, timedelta, date
from src.libs.database import Database 
from src.libs.redis2 import MyRedis as rs
from src.common.key import KEY

def today(): return datetime.now().strftime('%Y-%m-%d 00:00:00')
def next_day(tm=None):
    if not tm: tm = datetime.now()
    if type(tm) == type(""): tm = date(*(int(s) for s in tm.split("-"))) 
    tm1 = tm + timedelta(days=1)
    
    return str(tm1)[:10]

def id_null(d): return d == None or str(d) == '-1'

'''判断日报所属日期：第二天一定时间前提交的为前一天日报，tm - Datetime'''
def workday(tm=None):
    if not tm: tm = datetime.now()
    if tm.hour < C.RECORD_LAST_HOUR: tm = tm - timedelta(days=1) 
    return str(tm)[:10]

'''获取最近一周的时间'''
def weekday(tm=None):
    if not tm: tm = datetime.now()
    if type(tm) == type(""): tm = date(*(int(s) for s in tm.split("-")))    
    ds = tm.weekday() if tm.weekday() !=0 else 6
    '''若是星期一，且在10点之前，则时间周期定为上周''' 
    if tm.weekday() ==0 and tm.hour < 10: ds = 7
    tm1 = tm - timedelta(days=ds)
    
    return str(tm1)[:10], str(tm)[:10] 
    
    # if tm.wday == 0

def monthSection():
    now = datetime.now()
    begin = datetime(now.year, now.month, 1)
    end = datetime(now.year, now.month, calendar.monthrange(now.year, now.month)[1])
    if now.day < 8:
        end = begin - timedelta(days=1)
        begin = datetime(end.year, end.month, 1)   
    return str(begin)[:10], str(end)[:10]

def quarterSection(q=None):
    QUARTERS = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
    now = datetime.now()
    y, m = now.year, now.month;
    a, b = int(m / 3), m % 3;
    q = a if b > 1 else a - 1 
    if q < 0: y, q = y - 1, 3
    
    ms = QUARTERS[q]
    begin = datetime(y, ms[0], 1)
    end = datetime(y, ms[-1], calendar.monthrange(y, ms[-1])[1])
    end += timedelta(days=1)
    
    return str(begin), str(end) 
    

def get_user_level(user):
    info = rs.hget(KEY.USERS, user)
    return int(info['level'])

def get_user_org(user):
    info = rs.hget(KEY.USERS, user)
    return int(info['orgId'])

class Project():
    def __init__(self, id_=None, name="", create_user="", description=""):
        self.id = id_
        self.name = name
        self.create_user = create_user
        self.description = description
    
    def create(self):
        db = Database()
        sql = "insert into project (name, createUser, description) values (%s, %s, %s)"
        flag = db.execute(sql, (self.name, self.create_user, self.description))
        
        return flag
    
class Module():
    def __init__(self, project_id=None, id_=None, name="", create_user="", description=""):
        self.project_id = project_id 
        self.id = id_
        self.name = name
        self.create_user = create_user
        self.description = description
    
    def check_status(self, db):
        sql = "select status from project where id=%s"
        res = db.read_all(sql, [self.project_id])
        if len(res) != 1 or int(res[0]['status']) != 0: return False
        return True
    
    def create(self):
        db = Database()
        flag = self.check_status(db)
        if not flag: return -1, "该项目已关闭，请联系管理员开启"
          
        sql = "insert into module (projectId, name, createUser, description) values (%s, %s, %s, %s)"
        flag = db.execute(sql, (self.project_id, self.name, self.create_user, self.description))
        
        return flag, None
        
        
class Task():
    def __init__(self, project_id=None, module_id=None, id_=None):
        self.project_id = project_id
        self.module_id = module_id 
        self.id = id_
            
    def set_data(self, is_multi, name, create_user, description, plan_end_time, 
                 executor=None, depart=None):
        self.is_multi = is_multi
        self.name = name
        self.create_user = create_user
        self.description = description
        self.plan_end_time = plan_end_time 
        self.executor = executor if executor else self.create_user
    
    def check_status(self, db):
        sql = "select status from module where projectId=%s and id=%s"
        res = db.read_all(sql, [self.project_id, self.module_id])
        if len(res) != 1 or int(res[0]['status']) != 0: return False
        return True
        
    def create(self):
        db = Database()
        flag = self.check_status(db)
        if not flag: return -1, "该模块已关闭，请联系管理员开启"
        
        sql = "insert into task (projectId, moduleId, name, createUser, description, planEndTime, executor, multiUser) \
            values (%s, %s, %s, %s, %s, %s, %s, %s)"
        flag = db.execute(sql, (self.project_id, self.module_id, self.name, self.create_user
                                , self.description, self.plan_end_time, self.executor, self.is_multi))
        return flag, None
    

class WorkRecord():
    def __init__(self, category=0, project_id=None, module_id=None, task_id=None, id_=None):
        self.category = category
        self.project_id = project_id
        self.module_id = module_id 
        self.task_id = task_id
        self.id = id_
        self.task = None
        '''本表暂时设为空，理论上由任务表关联得出'''
        self.leader = None
        self.key = None
        
    def load_data(self, user, d):
        self.user = user
        self.category = d['type']
        self.project_id = d['pid']
        self.module_id = d['mid'] 
        self.task_id = d['tid']
        self.task = d['task']
        self.workday = workday() #str(datetime.now())[:10]
        self.progress = d['progress']
        self.content = d['content']
        self.mark = d.get('mark', None)
        self.key = d['key']
        self.project = d['project']
        self.module = d['module']
        
        '''若未选择任务，则使用文本填充于task字段，暂不开放填报日志时不选择任务直接新建任务'''
        if self.task_id == -1: self.task_id = None 
        
        
    def set_data(self, user, workday, progress, content="", mark="", leader=""):
        self.user = user
        self.workday = workday
        self.progress = progress
        self.content = content
        self.mark = mark 
        self.leader = leader
    
    def get_sql(self, idx=0):
        table = "plan_day" if idx else "record_day" 
        sql = '''insert into {} (user, workday, category, projectId, moduleId, taskId,
            task, progress, content, mark, leader, keycode, project, module) values 
            (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
        '''
        params = (self.user, self.workday, self.category, self.project_id, self.module_id, 
                    self.task_id, self.task, self.progress, self.content, 
                    self.mark, self.leader, self.key, self.project, self.module)
        return sql.format(table), params
     
     
    def create(self):
        db = Database()
        sql, params = self.get_sql()
        flag = db.execute(sql, params)
        return flag

        
# print(next_day())
        
# print(weekday("2021-10-23"))    
# p = Project("项目A", "lily", "Hello")
# p.create()

quarterSection()
        